﻿using Minecraft.Config;
using Minecraft.Config.Csv.CsvCls;
using Minecraft.Model;
using Minecraft.Model.Backpack;
using Minecraft.Model.ReqResp;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Minecraft.ServerHall.Cmd
{
	public class BackpackGoodsUse : CommandBase<MinecraftSession, StringRequestInfo>
	{
		public override string Name
		{
			get
			{
				return ProtocolHelper.GetProtocolStr(defCommand);
			}
		}
		private EnumCommand defCommand = EnumCommand.Backpack_BackpackGoodsUse;
		public override void ExecuteCommand(MinecraftSession session, StringRequestInfo requestInfo)
		{
			var req = requestInfo.GetRequestObj<BackpackGoodsUseReq>(session);
			if (req == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（原因：请求实体为空）" });
				return;
			}
			if (!session.minecraftSessionInfo.IsLogin)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（原因：未登录）" });
				return;
			}
			//物品来源判断
			if (!MinecraftConfig.enumGoodsSourceBelongsToTypeList.Any(m => m == req.enumGoodsBelongsToType))
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：物品来源不正确，前端传入的物品来源为【{req.enumGoodsBelongsToType.ToString()}】）" });
				return;
			}
			List<EnumGoodsType> goodsTypeList = EnumGoodsType.Food.GetEnumDesxriptionDict().Select(m => (EnumGoodsType)m.Key).ToList();
			////物品类型判断
			//if (!goodsTypeList.Any(m => m == req.enumGoodsType))
			//{
			//	session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：暂不支持该物品类型【{req.enumGoodsType.ToString()}】）" });
			//	return;
			//}
			if (req.goodsId.IsNullOrWhiteSpace())
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：goodsId 参数为空）" });
				return;
			}
			if (req.guid.IsNullOrWhiteSpace())
			{
				req.guid = "";
			}
			var goodsInfo = session.minecraftSessionInfo.goodsList.FirstOrDefault(m => m.enumGoodsBelongsToType_Convert == req.enumGoodsBelongsToType && m.GoodsId == req.goodsId && m.Num > 0 && m.guid == req.guid);
			if (goodsInfo == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：该物品信息不存在）" });
				return;
			}
			//var itemsInfo = CsvConfig.itemsList.FirstOrDefault(m => m.Id == goodsInfo.GoodsItemId);
			var itemsInfo = CsvConfig.GetMod_ItemsInfoById(goodsInfo.GoodsItemId);
			if (itemsInfo == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：该物品配置信息不存在）" });
				return;
			}
			//添加操作影响的positionOptList
			List<BackpackGoodsPositionOpt> positionOptList = new List<BackpackGoodsPositionOpt>();
			//家具使用后的响应信息
			BackpackGoodsUseFurnitureRespInfo backpackGoodsUseFurnitureRespInfo = new BackpackGoodsUseFurnitureRespInfo();
			List<KeyValueEnumAttributeInt> attributeList = new List<KeyValueEnumAttributeInt>();
			switch (itemsInfo.enumGoodsType_Convert)
			{
				case EnumGoodsType.Material:
					{
						session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：出现该错误的原因可能有：1、服务器暂未开发该功能，2、前端传入参数错误，3、没有更新model【{itemsInfo.enumGoodsType_Convert.ToString()}】）" });
						return;
					}
					break;
				case EnumGoodsType.Food:
					{
						var behavior = CsvConfig.GetMod_BehaviorInfoById(itemsInfo.Behavior_id);
						if (behavior == null)
						{
							session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：该食物的行为信息不存在）" });
							return;
						}
						switch (behavior.Id)
						{
							case "1100017":
								{

								}
								break;
							case "1110000":
								{
									//加生命值的regex
									Match match = Regex.Match(behavior.Behavior, @"AlterAttribute\(" + (int)EnumAttribute.CurHp + @"#(\d+)\)");
									if (!match.Success)
									{
										session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：EnumGoodsType.Food Regex不匹配）" });
										return;
									}
									var attrValue = int.Parse(match.Groups[1].Value);

									if (session.minecraftSessionInfo.player.Human_Life <= 0)
									{
										session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：session.minecraftSessionInfo.player.Human_Life <= 0）" });
										return;
									}
									session.minecraftSessionInfo.player.Human_Life += attrValue;
									if (session.minecraftSessionInfo.player.Human_Life > MinecraftConfig.PlayerInitHp)
									{
										session.minecraftSessionInfo.player.Human_Life = MinecraftConfig.PlayerInitHp;
									}
									attributeList.Add(new KeyValueEnumAttributeInt { key = EnumAttribute.CurHp, value = session.minecraftSessionInfo.player.Human_Life });
								}
								break;
							default:
								{
									session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：Id为【{behavior.Id}】的 behavior 解析还没开发）" });
									return;
								}
								break;
						}
						goodsInfo.Num--;
						positionOptList.Add(new BackpackGoodsPositionOpt
						{
							enumGoodsBelongsToType = goodsInfo.enumGoodsBelongsToType_Convert,
							GoodsPosition = goodsInfo.GoodsPosition,
							guid = goodsInfo.guid
						});
					}
					break;
				case EnumGoodsType.Equipment:
					{
						session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：出现该错误的原因可能有：1、服务器暂未开发该功能，2、前端传入参数错误，3、没有更新model【{itemsInfo.enumGoodsType_Convert.ToString()}】）" });
						return;
					}
					break;
				case EnumGoodsType.Weapon:
					{
						session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：暂未开发【{itemsInfo.enumGoodsType_Convert.ToString()}】）" });
						return;
					}
					break;
				case EnumGoodsType.Furniture:
					{
						//放置限制，//暂时注释，注释取消
						var map = session.minecraftSessionInfo.map;
						//if (map.SourceMapId != MinecraftConfig.BaseMapId)
						//{
						//	session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：只能在基地中放置家具，而玩家当前正处于id为【{session.minecraftSessionInfo.map.SourceMapId}】的地图中）" });
						//	return;
						//}
						//if (map.isBig_Convert)
						//{
						//	session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：玩家正处于大地图界面中，不允许操作）" });
						//	return;
						//}
						if (req.backpackGoodsUseFurnitureReqInfo == null)
						{
							session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：backpackGoodsUseFurnitureReqInfo 参数为空）" });
							return;
						}
						List<EnumFurnitureType> furnitureTypeList = EnumFurnitureType.Output.GetEnumDesxriptionDict().Select(m => (EnumFurnitureType)m.Key).ToList();
						//家具类型判断
						if (!furnitureTypeList.Any(m => m == req.backpackGoodsUseFurnitureReqInfo.enumFurnitureType))
						{
							session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：暂不支持该家具类型【{req.backpackGoodsUseFurnitureReqInfo.enumFurnitureType.ToString()}】）" });
							return;
						}
						if (req.backpackGoodsUseFurnitureReqInfo.point3 == null)
						{
							session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（backpackGoodsUseFurnitureReqInfo.point3参数为空）" });
							return;
						}
						//Mod_Furniture mod_Furniture = CsvConfig.furnitureList.FirstOrDefault(m => m.Id == goodsInfo.GoodsItemId);
						Mod_Drawing mod_Drawing = CsvConfig.GetMod_DrawingInfoById(goodsInfo.GoodsItemId);
						if (mod_Drawing == null)
						{
							session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（家具配置表中不存在该信息）" });
							return;
						}
						if (mod_Drawing.enumFurnitureType_Convert != req.backpackGoodsUseFurnitureReqInfo.enumFurnitureType)
						{
							session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（传入的家具类型和背包中将要建造的家具类型不一致，或者要使用的物品不是家具【mod_Furniture.enumFurnitureType_Convert：{mod_Drawing.enumFurnitureType_Convert}，req.backpackGoodsUseFurnitureReqInfo.enumFurnitureType：{req.backpackGoodsUseFurnitureReqInfo.enumFurnitureType}】）" });
							return;
						}
						var furnitureList = session.GetAllFurnitureConvergeList();
						//不允许同一位置判断
						if (furnitureList.Any(m => m.point3.Equals(req.backpackGoodsUseFurnitureReqInfo.point3)))
						{
							session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（基地中相同坐标点存在相同的建筑（只针对家具））" });
							return;
						}
						var furniture = furnitureList.FirstOrDefault(m => m.FurnitureId == goodsInfo.GoodsId);
						if (furniture != null)
						{
							session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（基地中已经有相同【{furniture.enumFurnitureType.ToString()}】家具id的建筑了）" });
							return;
						}
						//放置数量上限的判断，暂时注释掉
						//var count = furnitureList.Count(m => m.FurnitureItemId == goodsInfo.GoodsItemId);
						//if (mod_Drawing.Max_count_Convert > 0 && count >= mod_Drawing.Max_count_Convert)
						//{
						//	session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（家具放置数量已达上限）" });
						//	return;
						//}
						//添加操作影响的positionOptList
						positionOptList.Add(new BackpackGoodsPositionOpt
						{
							enumGoodsBelongsToType = goodsInfo.enumGoodsBelongsToType_Convert,
							GoodsPosition = goodsInfo.GoodsPosition,
							guid = goodsInfo.guid
						});

						goodsInfo.Num--;
						var newFurniture = new FurnitureModel
						{
							FurnitureId = session.GetNewFurnitureId(), // req.goodsId,
							FurnitureTypeId = (int)req.backpackGoodsUseFurnitureReqInfo.enumFurnitureType,
							FurnitureItemId = mod_Drawing.Id,
							Level = 1,
							PlayerId = session.minecraftSessionInfo.player.PlayerId,
							Point_X = req.backpackGoodsUseFurnitureReqInfo.point3.x,
							Point_Y = req.backpackGoodsUseFurnitureReqInfo.point3.y,
							Point_Z = req.backpackGoodsUseFurnitureReqInfo.point3.z,
							angle = req.backpackGoodsUseFurnitureReqInfo.angle,
							Hp = mod_Drawing.Hp_Convert,
							Output_MaterialGoodsItemIdsPosAndNums = "",
							Output_timeTicksStr = "",
							Output_ResultGoodsItemId = "",
							Output_ResultGoodsNum = 0,
							TreasureBox_IsPrefab = 0,
							TreasureBox_MapId = map.SourceMapId,
						};
						req.goodsId = newFurniture.FurnitureId;
						furnitureList.Add(newFurniture);

						//家具分类存储
						session.FurnitureClassify(furnitureList);

						backpackGoodsUseFurnitureRespInfo = new BackpackGoodsUseFurnitureRespInfo
						{
							angle = req.backpackGoodsUseFurnitureReqInfo.angle,
							point3 = req.backpackGoodsUseFurnitureReqInfo.point3,
							itemId = req.backpackGoodsUseFurnitureReqInfo.itemId,
							enumFurnitureType = req.backpackGoodsUseFurnitureReqInfo.enumFurnitureType
						};
					}
					break;
				default:
					{
						session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：出现该错误的原因可能有：1、服务器暂未开发该功能，2、前端传入参数错误，3、没有更新model【{itemsInfo.enumGoodsType_Convert.ToString()}】）" });
						return;
					}
					break;
			}

			//组装响应数据
			List<BackpackCellInfo> posGoodsinfoList = new List<BackpackCellInfo>();
			//获取影响的位置列表（只有两个，一个背包，一个家具）
			positionOptList.ForEach(optItem =>
			{
				if (optItem.enumGoodsBelongsToType == goodsInfo.enumGoodsBelongsToType_Convert)
				{
					//找到受影响的物品位置信息
					posGoodsinfoList = session.minecraftSessionInfo.goodsList.Where(m => m.enumGoodsBelongsToType_Convert == optItem.enumGoodsBelongsToType && m.GoodsPosition == optItem.GoodsPosition && m.guid == optItem.guid).GetBackpackGoodsCellInfo();
				}
				else
				{
					//不作处理    
				}
			});

			session.minecraftSessionInfo.goodsList.RemoveAll(m => m.Num <= 0);

			var resp = new BackpackGoodsUseResp
			{
				enumGoodsType = itemsInfo.enumGoodsType_Convert,
				goodsId = req.goodsId,
				goodsItemId = itemsInfo.Id,
				isFightUse = req.isFightUse,
				userId = req.userId,
				targetId = req.targetId,
				backpackShortcutBarCellInfoList = posGoodsinfoList,
				backpackGoodsUseFurnitureRespInfo = backpackGoodsUseFurnitureRespInfo,
				enumGoodsBelongsToType = req.enumGoodsBelongsToType,
				guid = req.guid,
				attributeList = attributeList,
			};
			session.Send(defCommand, req, resp);
		}
	}
}
